import { If } from '@/components';
import tool from '@/utils/tool';
import Icon from '@ant-design/icons';
import { Button } from 'antd';
import classNames from 'classnames';
import React from 'react';
import styles from './index.less';

export default class ButtonComponent extends React.Component {
  onClick = (e) => {
    const { onClick } = this.props;
    if (!onClick) {
      return;
    }
    let p = onClick(e);
    if (p && p.finally) {
      this.loading = true;
      this.setState({});
      p.finally(() => {
        this.loading = false;
        this.setState({});
      });
    }
  };
  render() {
    const {
      className,
      children,
      icon,
      onClick,
      type,
      loading,
      border,
      ...props
    } = this.props;
    let _loading = loading;

    if (tool.isPromise(loading) && this.loadingPromise != loading) {
      this.loadingPromise = loading;
      this.loading = true;
      loading.finally(() => {
        this.loading = false;
        this.setState({});
      });
    }

    if (this.hasOwnProperty('loading')) {
      _loading = this.loading;
    }

    let _type = type;
    if (border) {
      _type = _type + '-border';
    }
    return (
      <Button
        className={classNames(styles.btn, className, {
          [styles.border]: border,
        })}
        onClick={this.onClick}
        loading={_loading}
        type={_type}
        {...props}
      >
        <If condition={icon}>
          <span className="m-r-xxs">
            <Icon type={icon} />
          </span>
        </If>
        {children}
      </Button>
    );
  }
}
